package com.siwei.mes.service.laboratory.factory.concrete.service;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKyqd;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.concrete.DataConcreteKy;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.ConcreteLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.concrete.ConcreteLaboratoryFactory;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 混凝土抗压强度
 *
 * @Description: 混凝土抗压强度
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/28 22:08
 */
@Service
public class ConcreteKyqdFactory extends LaboratoryAbstractService implements ConcreteLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private ConcreteLaboratoryMapper concreteLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CONCRETE_PARAM_KYQD;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail) {
        log.info("开始上传到协会数据库：【混凝土-{}】", testProjectEnum.getName());
        ConcreteKyqd concreteKyqd = objJson.toJavaObject(ConcreteKyqd.class);

        if (concreteKyqd == null) {
            log.info("混凝土-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        DataConcreteKy dataConcreteKy = new DataConcreteKy();

        dataConcreteKy.setS1(1);
        dataConcreteKy.setS2(NullUtils.ifNull(concreteKyqd.getPjz28d()));
        dataConcreteKy.setS3(NullUtils.ifNull(concreteKyqd.getFyxs28d()));

        dataConcreteKy.setS28(NullUtils.ifNull(concreteKyqd.getZsbzqd28d()));
        dataConcreteKy.setConclusion(NullUtils.ifNull(concreteKyqd.getFyxs28d()));

        if (concreteKyqd.getSjcc() != null && !concreteKyqd.getSjcc().isEmpty()) {
            String sjcc = concreteKyqd.getSjcc();
            String val = "";
            if (sjcc.contains("100")) {
                val = "100";
            } else if (sjcc.contains("150")) {
                val = "150";
            } else if (sjcc.contains("200")) {
                val = "200";
            }

            dataConcreteKy.setS4(Integer.parseInt(val));
            dataConcreteKy.setS5(Integer.parseInt(val));
            dataConcreteKy.setS6(Integer.parseInt(val));
            dataConcreteKy.setS7(Integer.parseInt(val));
            dataConcreteKy.setS8(Integer.parseInt(val));
            dataConcreteKy.setS9(Integer.parseInt(val));
        }

        if (concreteKyqd.getQd28d() != null && !concreteKyqd.getQd28d().isEmpty()) {
            List<ConcreteKyqd.QdInfo> qd28d = concreteKyqd.getQd28d();
            for (ConcreteKyqd.QdInfo qdInfo : qd28d) {
                if (qdInfo.getIndex() != null && "1".equals(qdInfo.getIndex())) {
                    dataConcreteKy.setS13(NullUtils.ifNull(qdInfo.getHz()));
                    dataConcreteKy.setS16(NullUtils.ifNull(qdInfo.getQd()));
                } else if (qdInfo.getIndex() != null && "2".equals(qdInfo.getIndex())) {
                    dataConcreteKy.setS14(NullUtils.ifNull(qdInfo.getHz()));
                    dataConcreteKy.setS17(NullUtils.ifNull(qdInfo.getQd()));
                } else if (qdInfo.getIndex() != null && "3".equals(qdInfo.getIndex())) {
                    dataConcreteKy.setS15(NullUtils.ifNull(qdInfo.getHz()));
                    dataConcreteKy.setS18(NullUtils.ifNull(qdInfo.getQd()));
                }
            }
        }

        dataConcreteKy.setS10("符合要求");
        dataConcreteKy.setS11("符合要求");
        dataConcreteKy.setS12("符合要求");
        dataConcreteKy.setS19("破损");
        dataConcreteKy.setS20("破损");
        dataConcreteKy.setS21("破损");

        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataConcreteKy, "力学室", concreteKyqd.getJcrq(), detail);

        dataConcreteKy.setSampleName("混凝土立方体试件");

        Map<String, Object> data_jgcl_hnt_hntkyBySampleNo = concreteLaboratoryMapper.findDATA_JGCL_HNT_HNTKYBySampleNo(sampleNo);

        if (data_jgcl_hnt_hntkyBySampleNo == null) {
            concreteLaboratoryMapper.addDATA_JGCL_HNT_HNTKY(dataConcreteKy);
        } else {
            //修改
            concreteLaboratoryMapper.updateDATA_JGCL_HNT_HNTKY(dataConcreteKy);
        }


        //项目id 默认为0
        String parameterID = "0";

        String jcrq = concreteKyqd.getJcrq();

        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        DataDefaultUc defaultUc = new DataDefaultUc();
        defaultUc.setConclusion(concreteKyqd.getDxjl7d());
        defaultUc.setUcResultValue(concreteKyqd.getDxjl7d());
        defaultUc.setUcTestValue(concreteKyqd.getPjz7d());

        //获取标准值
        for (CheckBatchConfig projectInfo : batchConfigList) {
            if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KYQD.getCode())) {
                defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
            }
        }

        //根据物料信息设置判断配置
        for (TestProjectSpecConfig test : testProjectSpecConfigList) {
            if (TestProjectEnum.CONCRETE_PARAM_KYQD.getCode().equals(test.getTestProjectCode())) {
                if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                    String json = test.getObjJson();
                    super.setUcStandardValue(defaultUc, json, "kyqd");
                }
            }
        }

        //赋值
        super.setDefUc(defaultUc, experiment, "力学室", sampleNo, jcrq, detail);

        defaultUc.setUcParameterID(parameterID);//项目id

        defaultUc.setSampleName("混凝土立方体试件");

        //新增或修改DataDefaultUc
        super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap) {
        log.info("开始下载协会数据到品控：【混凝土-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        ConcreteKyqd concreteKyqd = objJson.toJavaObject(ConcreteKyqd.class);
        if (concreteKyqd == null) {
            log.info("【混凝土-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }
        //根据样品编码查询协会混凝土抗压强度信息
        Map<String, Object> data = concreteLaboratoryMapper.findDATA_JGCL_HNT_HNTKYBySampleNo(sampleNo);

        if (data == null) {
            log.info("根据样品编码查询协会混凝土抗压强度信息为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }

        concreteKyqd.setPjz28d(NullUtils.ifNull(data.get("S2")));
        concreteKyqd.setFyxs28d(NullUtils.ifNull(data.get("S3")));

        if (data.get("S4") != null && data.get("S7") != null) {
            concreteKyqd.setSjcc(data.get("S4").toString() + "*" + data.get("S7").toString() + "*" + data.get("S7").toString());
        }

        concreteKyqd.setZsbzqd28d(NullUtils.ifNull(data.get("S28")));

        if (data.get("DetectonDate") != null) {
            Date detectonDate = (Date) data.get("DetectonDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            concreteKyqd.setJcrq(strDate);
        }

        if (concreteKyqd.getQd28d() != null && !concreteKyqd.getQd28d().isEmpty()) {

            List<ConcreteKyqd.QdInfo> qd28d = concreteKyqd.getQd28d();

            for (ConcreteKyqd.QdInfo qdInfo : qd28d) {
                if (qdInfo.getIndex() != null && "1".equals(qdInfo.getIndex())) {
                    qdInfo.setHz(NullUtils.ifNull(data.get("S13")));
                    qdInfo.setQd(NullUtils.ifNull(data.get("S16")));
                } else if (qdInfo.getIndex() != null && "2".equals(qdInfo.getIndex())) {
                    qdInfo.setHz(NullUtils.ifNull(data.get("S14")));
                    qdInfo.setQd(NullUtils.ifNull(data.get("S17")));
                } else if (qdInfo.getIndex() != null && "3".equals(qdInfo.getIndex())) {
                    qdInfo.setHz(NullUtils.ifNull(data.get("S15")));
                    qdInfo.setQd(NullUtils.ifNull(data.get("S18")));
                }
            }
        }

        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(concreteKyqd);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data.get("AccessRuleCode")));

        if (parameterMap.containsKey(detail.getTestProjectCode())) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }

        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
